<?php

declare(strict_types=1);

namespace App\Resource\Service;

use App\Activity\Model\ActivityModel;
use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\ShopGroupModel;
use App\Resource\Model\ShopModel;

class ShopGroupService extends BaseService
{
    /**
     * @param array $where
     * @param int $perPage
     * @param array|string[] $field
     *
     * @return array
     */
    public function getList(array $where, int $perPage = 15, array $field = ['*'])
    {
        $query = ShopGroupModel::query();
        !empty($where['shop_group_name']) && $query->whereRaw('INSTR(shop_group_name, ?) > 0', [$where['shop_group_name']]);
        $list = $query->paginate($perPage, $field);

        return ['code' => ErrorCode::SUCCESS, 'data' => $list];
    }

    /**
     * 店群详情，并且包括这个店群下的门店
     * @param int $shopGroupId
     *
     * @return array
     */
    public function getInfoById(int $shopGroupId)
    {
        $shopGroupInfo = ShopGroupModel::query()->where('id', $shopGroupId)->first();
        if (!$shopGroupInfo) {
            return ['code' => ErrorCode::NOT_EXIST];
        }
        $shopsInGroup = ShopModel::where(['shop_group_id' => $shopGroupInfo->id, 'is_deleted' => 0])
            ->select('shop_id', 'shop_name', 'shop_man', 'address', 'shop_tel')->get();
        $shopGroupInfo->shop_list = $shopsInGroup;

        return ['code' => ErrorCode::SUCCESS, 'data' => $shopGroupInfo];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function add(array $params)
    {
        $res = ShopGroupModel::create([
            'shop_group_name' => $params['shop_group_name'],
        ]);

        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => [], 'info' => ['target_id' => $res -> id]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function update(array $params)
    {
        $res = ShopGroupModel::where(['id' => $params['id']])
            ->update([
                'shop_group_name' => $params['shop_group_name'],
            ]);
        if (!$res) {
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => [], 'info' => ['target_id' => $params['id']]];
    }


    /**
     * 获取所选店群下的店铺
     * @param array $params
     * @return array
     *
     * 说明：若传 start_time 等时间参数，则判断店铺结果列表中
     */
    public function getShopListByGroup(array $params)
    {
        $crossShopIds = [];
        $crossShops = [];
        $params['activity_type'] = isset($params['activity_type']) ? $params['activity_type'] : '';
        // 若店铺列表中存在和所传时间重合的活动，则给予标记
//        if(!empty($params['start_time'])){
        if(!empty($params['start_time']) && $params['activity_type'] == 4){
            $date = $params['start_time'];
            // 1、筛选出活动日期相同的秒杀活动，不包含已禁用的活动
            $activityList = ActivityModel::query()
                ->select(['activityID', 'shop_ids', 'activity_prams'])
                ->where('is_deleted', 0)
                ->where('activityType', 4)
                ->when($params['edit_sign'] ?? 0, function ($query, $editSign) {
                    return $query->whereNotIn('activityID', [$editSign]);
                })
                ->whereIn('status', [1,2])
                ->whereRaw('INSTR(begin_date, ?) > 0', [$date])
                ->get()->toArray();

            // 2、筛选出活动时间相同的活动

            // 指定的开始时间和结束时间
            $startTime = $date.' '.$params['s_time'];
            $endTime = $date.' '.$params['e_time'];

            // 拼接活动的时间，并检测时间是否重合
            foreach ($activityList as $key => $val){
                $actTime = json_decode($val['activity_prams'], true);
                $activityList[$key]['act_start_time'] = $date.' '.$actTime['start_time'];
                $activityList[$key]['act_end_time'] = $date.' '.$actTime['end_time'];
                $isTimeCross = $this -> isTimeCross($startTime, $endTime, $activityList[$key]['act_start_time'], $activityList[$key]['act_end_time']);
                if($isTimeCross){
                    // 时间冲突
                    $shopIdArr = explode(',', $val['shop_ids']);
                    foreach($shopIdArr as $k => $v){
                        array_push($crossShopIds,$v);
                    }
                }
            }
            $crossShops = array_unique($crossShopIds);
        }

        if($params['activity_type'] == 5){
            // 当前操作活动的开始和结束时间
            $startTime = trim(substr($params['start_time'], 0, 19));
            $endTime = trim(substr($params['start_time'], -19));

            // 1、查出活动进行中和未开始的免单活动，不包含已禁用和已结束的活动
            $activityList = ActivityModel::query()
                ->select(['activityID', 'shop_ids', 'begin_date', 'end_date'])
                ->where('is_deleted', 0)
                ->where('activityType', $params['activity_type'])
                ->when($params['edit_sign'] ?? 0, function ($query, $editSign) {
                    return $query->whereNotIn('activityID', [$editSign]);
                })
                ->whereIn('status', [1,2])
                ->get();

            if(!$activityList -> isEmpty()){
                // 拼接活动的时间，并检测时间是否重合
                foreach ($activityList as $key => $val){
                    $isTimeCross = $this -> isTimeCross($startTime, $endTime, $val['begin_date'], $val['end_date']);
                    if($isTimeCross){
                        // 时间冲突
                        $shopIdArr = explode(',', $val['shop_ids']);
                        foreach($shopIdArr as $k => $v){
                            array_push($crossShopIds,$v);
                        }
                    }
                }
            }

            $crossShops = array_unique($crossShopIds);
        }

        //--------------------------------------------------------------------------------------------------------------

        if(!$params['shop_group_ids']){
            return ['code' => ErrorCode::SYSTEM_INVALID];
        }
        $shopGroups = $params['shop_group_ids'];
        $shopGroupsArr = explode(',', $shopGroups);
        $shopList = ShopModel::whereIn('shop_group_id', $shopGroupsArr)->where(['is_deleted' => 0])
            ->select(['shop_id', 'shop_name', 'shop_group_id', 'shop_man', 'shop_tel', 'province', 'city', 'country', 'address', 'shop_desc'])
            ->get()
            ->toArray();
        $shopListInfo = [];
        foreach ($shopList as $key => $val) {
            $shopListInfo[$key]['shop_id'] = $val['shop_id'];
            $shopListInfo[$key]['shop_name'] = $val['shop_name'];
            $shopListInfo[$key]['shop_group_id'] = $val['shop_group_id'];
            $shopListInfo[$key]['shop_group_name'] = $this->getGroupNameByGroupId($val['shop_group_id']);
            $shopListInfo[$key]['shop_man'] = $val['shop_man'];
            $shopListInfo[$key]['shop_tel'] = $val['shop_tel'];
            $shopListInfo[$key]['shop_address'] = $this->getAddress($val['province'], $val['city'], $val['country'], $val['address']);
            $shopListInfo[$key]['shop_desc'] = $val['shop_desc'];
            if(!empty($params['start_time']) && in_array($val['shop_id'], $crossShops)){
                $shopListInfo[$key]['is_time_cross'] = true;
            }else{
                $shopListInfo[$key]['is_time_cross'] = false;
            }
        }

        return ['code' => ErrorCode::SUCCESS, 'data' => $shopListInfo];
    }

    /**
     * PHP计算两个时间段是否有交集
     *
     * @param string $beginTime1 开始时间1
     * @param string $endTime1 结束时间1
     * @param string $beginTime2 开始时间2
     * @param string $endTime2 结束时间2
     * @return bool
     */
    public function isTimeCross($beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = '')
    {

        $beginTime1 = strtotime($beginTime1);   // 指定的开始时间
        $endTime1 = strtotime($endTime1);   // 指定的结束时间
        $beginTime2 = strtotime($beginTime2);   // 活动的开始时间
        $endTime2 = strtotime($endTime2);   // 指定的结束时间

//        var_dump($beginTime1);
//        var_dump($endTime1);
//        var_dump($beginTime2);
//        var_dump($endTime2);die;

        $status = $beginTime2 - $beginTime1;
        if ($status > 0) {
            $status2 = $beginTime2 - $endTime1;
            if ($status2 >= 0) {
                return false;
            } else {
                return true;
            }
        } else {
            $status2 = $endTime2 - $beginTime1;
            if ($status2 > 0) {
                // 有冲突
                return true;
            } else {
                // 无冲突
                return false;
            }
        }
    }




}
